package com.freeman.cement.config;

import com.freeman.cement.system.BllFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
public class CacheConfig {
    private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);
    
    // 缓存过期时间（分钟）
    private static final long CACHE_EXPIRATION_MINUTES = 48 * 60; // 48小时
    
    /**
     * 每5分钟执行一次缓存清理
     */
    @Scheduled(fixedRate = 300000)
    public void cleanExpiredCache() {
        logger.info("开始清理过期缓存，当前缓存大小: {}", BllFrame.loginUsrsCache.size());
        if (BllFrame.loginUsrsCache.isEmpty()) {
            logger.warn("缓存为空，请检查用户登录状态");
            return;
        }
        
        Date now = new Date();
        BllFrame.loginUsrsCache.entrySet().removeIf(entry -> {
            Date lastActiveTime = entry.getValue().getLastActiveTime();
            if (lastActiveTime == null) {
                logger.warn("用户[{}]的最后活动时间为空，将被清理", entry.getKey());
                return true;
            }
            long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(now.getTime() - lastActiveTime.getTime());
            boolean expired = diffInMinutes > CACHE_EXPIRATION_MINUTES;
            if (expired) {
                logger.info("清理过期用户缓存: {}, 最后活动时间: {}, 已过期: {}分钟", 
                    entry.getKey(), lastActiveTime, diffInMinutes);
            }
            return expired;
        });
        logger.info("缓存清理完成，当前缓存大小: {}", BllFrame.loginUsrsCache.size());
    }
} 